dojo.require("dojo.DeferredList");

dojo.provide("slipstream.data.StoreManager");
dojo.declare("slipstream.data.StoreManager", null, {
	lang: 'sv',
    source: '/api/ifc',
	stores: {},
	scope: window,
	//globalstores: true,
	constructor: function(params,srcNodeRef){
		dojo.mixin(this, params);
	},
	generate: function(store){
		console.info('Starting storage manager')
		//console.info('Scope',this.scope)
		var deferred = new dojo.Deferred();
		var queue=[];
		if(dojo.isArray(store)){
			dojo.forEach(store,function(item,index,array){
				queue.push(this.load(item));
			},this);
		} else {
			queue.push(this.load());
		}
		//console.log(queue);
		var dl=new dojo.DeferredList(queue);
		var _onload=this.onLoad;
		dl.addCallback(function(){
			deferred.callback({
				success: _onload()
			})
		});
		//console.log('DF2',deferred);
		return deferred;
	},
	load: function(store){
		var xhrArgs = {
            url: (store!=undefined?this.source+'/'+store:this.source)+'.json',
            handleAs: "json",
			preventCache: false,
            error: function(error){
				console.error(error);
            }
        };
		if(store!=undefined){
			xhrArgs.load=dojo.hitch(this,function(item){
				this.createStore(item);
			});
		} else {
			xhrArgs.load=dojo.hitch(this,function(data){
				console.log(data);
				for (var i in data) {
					this.createStore(data[i]);
				}
				/*
				dojo.forEach(data,function(item,index){
					this.createStore(item);
				},this);
				*/
			});
		}
		//console.log(xhrArgs);
       	return new dojo.xhrGet(xhrArgs);
	},
	createStore: function(item){
		var name=item.name+'Store';
		//var buildstring=(this.globalstores?name+'=':'')+'new '+(this.engine!=undefined?this.engine:item.settings.engine)+'(item.arguments);';
		var buildstring='new '+(this.engine!=undefined?this.engine:item.settings.engine)+'(item.arguments);';
		//console.log(buildstring);
		console.log(name,eval(buildstring));
		this.stores[name]=eval(buildstring);
		this.stores[name].lang=this.lang;
		this.stores[name].ss_settings=item.settings;
		this.scope[name]=this.stores[name];
	},
	onLoad: function(res){
		console.log(res);
		return true;
	}
});
